// Powered by 张迎战
import
    axios from "axios";
import {Toast} from "vant";
import "vant/es/toast/style/index";
import AuthAPI from "./userApi";
import {getUserInfoBase} from "@/stores/user.js";

function getToken() {
    const user = getUserInfoBase()
  //  console.log(11, user.token)
    if (user) {
        return user.token;
    } else {
        return null;
    }
}

let waitingCount = 0;

function startWaiting() {
    if (waitingCount++ <= 0) {
        Toast.loading({
            mask: false,
            duration: 0,// 一直存在
            forbidClick: true, // 禁止点击
            loadingType: "spinner",
            message: "加载中...",
        });
        waitingCount = 0;
    }
}

function endWaiting(isFeedback) {
    if (isFeedback) {
        if (--waitingCount <= 0) {
            Toast.clear();
        }
    } else {
        // 延迟关闭等待框，避免在多个连续请求间隔间闪烁
        setTimeout(() => endWaiting(true), 1000);
    }
}

 export const baseUrl = "http://39.107.205.180:9043/";

export function initHttp() {
    console.log("baseUrl->", baseUrl);
    // service 循环遍历输出不同的请求方法
    const instance = axios.create({
        baseURL: baseUrl,
        timeout: 600000,
    });
    const Http = {}; // 包裹请求方法的容器

    const myApi = [AuthAPI];

    for (const ii in myApi) {
        // 请求格式/参数的统一
        for (const key in myApi[ii]) {
            const api = myApi[ii][key]; // url method
            // async 作用：避免进入回调地狱
            Http[key] = async function (
                params, // 请求参数 get：url，put，post，patch（data），delete：url
                isFormData = false, // 标识是否是form-data请求
                config = {}, // 配置参数
            ) {
                let newParams = {};

                //  content-type是否是form-data的判断
                if (params && isFormData) {
                    newParams = new FormData();
                    for (const i in params) {
                        newParams.append(i, params[i]);
                    }
                } else {
                    newParams = params;
                }
                // 不同请求的判断
                let response = {}; // 请求的返回值
                if (api.method === "put" || api.method === "post" || api.method === "patch") {
                    try {
                        response = await instance[api.method](api.url, newParams, config);
                    } catch (err) {
                        await router.push("/");
                        response = err;
                    }
                } else if (api.method === "delete" || api.method === "get") {
                    config.params = newParams;
                    try {
                        response = await instance[api.method](api.url, config);
                        if (typeof response === undefined) {
                            // Toast("列表数据为空,请添加基础数据!");
                            await router.push("/");

                        }
                    } catch (err) {
                        await router.push("/");
                        response = err;
                    }
                }
                return response; // 返回响应值
            };
        }
    }

    // 请求拦截器
    instance.interceptors.request.use(
        (config) => {
            if (getToken()) {
                config.headers["Authorization"] = "Bearer " + getToken();
            }
            startWaiting();
            return config;
        },
        (error) => {
            // 请求错误
            endWaiting();
            Toast("请求错误，请求稍后重试!");
        },
    );
    // 响应拦截器
    instance.interceptors.response.use(
        (res) => {
            // 请求成功
            endWaiting();
            if (res.data.error) {
                //    window.location.href = "/";
                Toast("请求错误，请求稍后重试!");
                return;
            }
            // 查询用户授权时返回301不能跏
            return res.data;
        },
        (error) => {
            endWaiting();
            Toast("请求错误，请求稍后重试!");
            window.open("/login", "_top");
        },
    );

    return Http;
}

const Http = initHttp();
export default Http;
